package com.tjshop.android.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

	private static final String DB_NAME = "jinshaBook.db";
	private static final int VERSION = 1;
	private static DBHelper mInstance;
	private static String TAG = "DBHelper";

	// 创建用户表
	private final String CREATE_USER = "CREATE TABLE IF NOT EXISTS [users] ("
			+ "[id] [varchar(100)]," + "[name] [varchar(100)],"
			+ "[type] [varchar(100)]," + "[id_str] [varchar(100)],"
			+ "[add_time] [VARCHAR(100)]," + "[login_time] [VARCHAR(100)])";

	/**
	 * 构造器
	 * 
	 * @param context
	 */
	protected DBHelper(Context context) {
		super(context, DB_NAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(CREATE_USER);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		// TODO Auto-generated method stub
		db.execSQL("DROP TABLE IF EXISTS users");
		onCreate(db);

	}

	public synchronized int getCount(String tableName) {
		Log.d(TAG, "getCount");
		int count = -1;
		Cursor c = getReadableDatabase().query(tableName, null, null, null,
				null, null, null);
		if (c.moveToFirst()) {
			count = c.getCount();
		}
		c.close();
		c = null;
		return count;
	}

	public synchronized static DBHelper getInstance(Context context) {

		if (mInstance == null) {
			mInstance = new DBHelper(context);
		}
		return mInstance;
	}

	public synchronized static void destoryInstance() {
		if (mInstance != null) {
			mInstance.close();
		}
	}

	public synchronized void insert(String tablename, ContentValues values) {
		Log.d(TAG, "insert");
		getWritableDatabase().insert(tablename, null, values);
	}

	public synchronized void delete(String tablename, String wheres,
			String[] args) {
		Log.d(TAG, "delete");
		getWritableDatabase().delete(tablename, wheres, args);
	}

	public synchronized void update(String tablename, ContentValues values,
			String wheres, String[] args) {
		Log.d(TAG, "update");
		getWritableDatabase().update(tablename, values, wheres, args);
	}

	public synchronized Cursor query(String sql, String[] args) {
		Log.d(TAG, "query");
		Cursor cursor = getWritableDatabase().rawQuery(sql, args);
		return cursor;
	}

	public synchronized void execSQL(String sql, String[] args) {
		Log.d(TAG, "execSQL");
		getWritableDatabase().execSQL(sql, args);
	}

}
